<template>
  <div class="base-material">
    <el-row style="paddingBottom: 0">
      <el-col :span="24">
        <dynForm :info-form="searchForm" :search-tags="searchTags" :select-list="selectList">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleSearch"
          >
            {{ $t("search") }}</el-button
            >
        </dynForm>
      </el-col>
    </el-row>
    <div class="table-buttons">
      <el-button
        v-btnPermission:add
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >{{ $t("add") }}</el-button>
      <el-button
        v-btnPermission:edit
        :disabled="UpdateDisabled"
        type="primary"
        icon="el-icon-edit"
        @click="handleEdit"
      >{{ $t("modify") }}</el-button>
      <el-button
        v-btnPermission:onBoard
        type="primary"
        icon="el-icon-download"
        @click="handleOnBoard"
      >{{ $t("onBoard") }}</el-button>
      <el-button
        v-btnPermission:disembark
        type="primary"
        icon="el-icon-download"
        @click="handleDisembark"
      >{{ $t("Disembark") }}</el-button>
      <el-button
        v-btnPermission:startTime
        :disabled="DeleteDisabled"
        type="primary"
        @click="handleTiming"
      >{{ $t("start_the_timer") }}</el-button>
      <el-button
        v-btnPermission:delete
        :disabled="DeleteDisabled"
        type="danger"
        icon="el-icon-delete"
        @click="handleDelete"
      >{{ $t("delete") }}</el-button>
      <el-button
        v-btnPermission:add
        type="primary"
        icon="el-icon-download"
        @click="handleDownloadTemp"
      >{{ $t('downloadTemp') }}</el-button>
      <el-upload
        :action="baseApi + '/mtms/Upload/Submit?name=MaterialBaseList'"
        :headers="headers"
        :show-file-list="false"
        :on-success="uploadSuccess"
        :on-error="importFail"
        class="upload-btn"
        style="display: inline-block"
        accept=".xlsx"
      >
        <el-button
          v-btnPermission:add
          type="primary"
          icon="el-icon-upload"
        >{{ $t("import") }}</el-button
        >
      </el-upload>
      <el-button
        v-btnPermission:add
        type="primary"
        icon="el-icon-download"
        @click="handleExport"
      >{{ $t('export') }}</el-button>
    </div>
    <!-- 表单部分 -->
    <el-card shadow="never">
      <el-row>
        <dynTable
          ref="dynTable"
          :loading="tableLoading"
          :table-data="tableData"
          :table-columns="tableColumns"
          :handle-selection-change="handleSelectionChange"
          :row-click="rowClick"
        />
      </el-row>
      <pagination
        :total="total"
        :page.sync="listQuery.page"
        :size.sync="listQuery.size"
        @pagination="onchangePage"
      />
    </el-card>
    <baseMaterialForm ref="baseMaterialForm" @initList="initList"/>
    <materialOnModal ref="materialOnModal" @initList="initList"/>
    <materialOffModal ref="materialOffModal" @initList="initList"/>
  </div>
</template>

<script>
import mySetting from '@/mixins/mySetting'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { download } from '@/api/system/user'
import { getInitList, doDelete, getMaterialTypes, startCountDown } from '@/api/materialManagement/baseMaterial'
import materialOnModal from './component/materialOn.vue'
import materialOffModal from './component/materialOff.vue'
export default {
  name: 'BaseMaterial',
  components: {
    materialOnModal,
    materialOffModal,
    baseMaterialForm: () => import('./component/baseMaterialForm')
  },
  mixins: [mySetting],
  data() {
    return {
      searchForm: {},
      searchTags: [
        { label: this.$t('materialCode'), prop: 'code', tag: 'DynInput' },
        { label: this.$t('materialType'), prop: 'materialTypeId', tag: 'DynSelect' }
      ],
      selectList: {},
      tableColumns: Object.freeze(
        [
          { prop: '', label: '', type: 'selection' },
          { prop: '', label: this.$t('index'), type: 'index', width: '50px', templete: (_scope) => {
            return (
              <span>{ (this.listQuery.page - 1) * this.listQuery.size + _scope.$index + 1 }</span>
            )
          } },
          { prop: 'materialCode', label: this.$t('materialCode'), width: '140px' },
          { prop: 'materialTypeName', label: this.$t('materialType'), width: '140px' },
          { prop: 'eqpId', label: this.$t('eqpName'), width: '110px' },
          { prop: 'supplierName', label: this.$t('supplierName'), width: '140px' },
          { prop: 'supplierBatchNumber', label: this.$t('supplierBatchNumber'), width: '140px' },
          { prop: 'purchaseOrder', label: this.$t('purchaseOrderNo'), width: '140px' },
          { prop: 'iniLength', label: this.$t('iniLength'), width: '140px' },
          { prop: 'currentLength', label: this.$t('currentLength'), width: '140px' },
          { prop: 'productionDate', label: this.$t('productionDate'), width: '180px' },
          { prop: 'expireDate', label: this.$t('expireDate'), width: '180px' },
          { prop: 'creator', label: this.$t('creator'), width: '140px' },
          { prop: 'createTime', label: this.$t('createTime'), width: '180px' }
        ]
      ),
      tableLoading: true,
      headers: {
        Token: getToken()
      }
    }
  },
  computed: {
    ...mapGetters(['baseApi'])
  },
  created() {
    this.initList()
    this.getMaterialTypesList()
  },
  methods: {
    handleSearch() {
      this.listQuery.page = 1
      this.initList()
    },
    async initList() {
      const res = await getInitList(this.$clearNull({ ...this.searchForm, ...this.listQuery }))
      this.tableData = res.data
      this.total = res.total
      this.tableLoading = false
    },
    handleCreate() {
      this.$refs.baseMaterialForm.handleOpen()
    },
    handleEdit() {
      this.$refs.baseMaterialForm.handleOpen(this.multipleSelection[0])
    },
    handleOnBoard() {
      this.$refs.materialOnModal.handleOpen()
    },
    handleDisembark() {
      this.$refs.materialOffModal.handleOpen()
    },
    handleTiming() {
      const ids = this.multipleSelection.map(ele => ele.id)
      startCountDown({ ids }).then(res => {
        this.$betterTips(res)
      })
    },
    handleDelete() {
      this.$confirm(
        `${this.$t('confirmDelete')}${this.multipleSelection.length}${this.$t(
          'recordCount'
        )}?`,
        this.$t('tip'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      ).then(() => {
        const ids = this.multipleSelection.map(ele => ele.id)
        doDelete({ ids }).then(res => {
          this.$betterTips(res, this.setOnePage, this.initList)
        })
      })
    },
    handleSelectionChange(row) {
      this.multipleSelection = row
    },
    rowClick(row) {
      this.$refs.dynTable.$refs.multipleTable.toggleRowSelection(row)
    },
    onchangePage(page) {
      this.listQuery = page
      this.initList()
    },
    async handleDownloadTemp() {
      const res = await download({ name: 'MaterialBaseList' })
      window.open(this.baseApi + '/' + res.data)
    },
    uploadSuccess(response, file, fileList) {
      if (response.code !== 1) {
        const h = this.$createElement
        const listVNode = response.data.map((item) => {
          return (
            <p style={ { width: '240px' }}>
              <span style={ { width: '100%', wordWrap: 'break-word' }}>{item.index ? `第{${item.index}}行` : ''}{this.$t(item.msgCode)}</span>
            </p>
          )
        })
        const styles = {
          color: 'teal',
          overflowX: 'hidden',
          overflowY: 'auto',
          width: '280px',
          maxHeight: 'calc(100vh - 120px)'
        }
        this.$notify({
          message: h('div', { style: styles }, listVNode),
          type: 'error',
          duration: 0
        })
        fileList = []
      } else {
        this.$betterTips(response, this.initList)
      }
    },
    importFail() {
      this.$notify({
        message: this.$t('uploadFail'),
        type: 'error',
        duration: 3500
      })
    },
    async handleExport() {
      const res = await getInitList(this.$clearNull({ ...this.listQuery, ...this.infoForm, toexcel: 1 }))
      window.open(this.baseApi + '/' + res.data)
    },
    // 获取材料类型
    async getMaterialTypesList() {
      const res = await getMaterialTypes()
      this.$set(this.selectList, 'materialTypeId', res.data)
    }
  }
}
</script>
<style scoped lang="scss">
@import "~@/assets/styles/defaultStyle.scss";
::v-deep .el-form {
  padding-top: 10px;
  //     .el-form-item{
  //       margin-bottom: 15px;
  // }
}
.upload-btn{
  margin: 0 10px;
}
</style>
